package com.example.demo_text;

import java.sql.*;
import java.util.*;

public class AnswerDAO {
    private static Connection conn;

    static {
        try {
            conn = DriverManager.getConnection(databaseaccess.DatabaseUrl2, databaseaccess.DatabaseUser2, databaseaccess.DatabasePassword2);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void addAnswer(int questionId, String content) {
        String sql = "INSERT INTO question_ans (question_id, answer_content) VALUES (?, ?)";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, questionId);
            stmt.setString(2, content);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static List<Answer> getAnswersByQuestionId(int questionId) {
        List<Answer> answers = new ArrayList<>();
        String sql = "SELECT * FROM question_ans WHERE question_id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, questionId);
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                Answer ans = new Answer();
                ans.setAnsId(rs.getInt("ans_id"));
                ans.setQuestionId(rs.getInt("question_id"));
                ans.setAnswerContent(rs.getString("answer_content"));
                ans.setAnswerTime(rs.getTimestamp("answer_time"));
                answers.add(ans);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return answers;
    }
}
